package com.cqc.jdk8.Jutil.stream;

import org.junit.Test;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author cui
 * @date 2024/6/30 12:18
 * @description
 **/
public class SkipTest {

    @Test
    public void skipLimit() {
        String[] arr = {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
        List<String> list = Stream.of(arr)
                .skip(2)
                .limit(5)
                .collect(Collectors.toList());
        //[c, d, e, f, g]
        System.out.println(list);
    }

    /**
     * skip相当于分页的offset，可以变相的实现手动分页
     */
    @Test
    public void skipLimit2() {
        String[] arr = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};

        int pageSize = 2;//每页2条数据
        int total = arr.length;//总数据量
        //计算总页数的3种方法
        int totalPage = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        totalPage = (totalPage + pageSize - 1) / pageSize;
        totalPage = (int) Math.ceil((double) total / pageSize);


        for (int i = 1; i <= totalPage; i++) {
            int currentPage = i;//当前页码
            int offset = (currentPage - 1) * pageSize;//偏移量
            Stream.of(arr)
                    .skip(offset)
                    .limit(2)
                    .forEach(System.out::println);
            System.out.println("------------");
        }
    }
}
